from datetime import datetime

from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from clazz.models import Clazz
from clazz.serializers import ClazzSerializers
from user.models import User

from user.serializers import UserSerializers


# Create your views here.


class ClassView(ModelViewSet):
    queryset = Clazz.objects.all()
    serializer_class = ClazzSerializers

    # 设置权限 ,登录允许任何人访问
    permission_classes = [AllowAny]

    # 重写查询所有的方法
    @action(methods=['GET'], detail=False, url_path='available-list', url_name='available-list')
    def available(self, request, *args, **kwargs):
        # 查询所有可用的班级,没有毕业的班级,没有上出的班级
        queryset = self.get_queryset().filter(is_delete=False, state=False)
        # 序列化满足条件的数据
        serialize = self.get_serializer(queryset, many=True)
        return Response(data=serialize.data, status=status.HTTP_200_OK)


class ClazzViewSet(ModelViewSet):
    queryset = Clazz.objects.all()
    serializer_class = ClazzSerializers

    # 分页
    pagination_class = PageNumberPagination
    PageNumberPagination.page_size_query_param = 'rows'

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset().filter(is_delete=False).order_by('state', 'create_time')

        # 进行分页
        paginate = self.paginate_queryset(queryset)
        if paginate is None:
            return Response(data={"message": "该请求必须进行分页操作"}, status=status.HTTP_400_BAD_REQUEST)

        # 对分页后的结果 进行序列化
        serializer = self.get_serializer(paginate, many=True)
        # 返回分页后的结果
        return self.get_paginated_response(serializer.data)

    # 添加班级
    def create(self, request, *args, **kwargs):
        # 查询班级名 是否 已添加 (删除状态是False,查询没有删除的名字是否有重名的)
        queryset = self.get_queryset().filter(name=request.data['name'], is_delete=False)

        if queryset:
            return Response(data={"message": "班级名已存在"}, status=status.HTTP_400_BAD_REQUEST)
        return super().create(request, *args, **kwargs)

    # 在修改班级中,要首先查询到要修改的班级内容
    @action(methods=['GET'], detail=False, url_path='edit-clazz', url_name='edit-clazz')
    def get_edit_class(self, request, *args, **kwargs):
        # 根据id查询数据
        # 正确获取GET请求的查询参数
        ids = request.query_params.get('id')
        if ids is not None:
            queryset = self.get_queryset().filter(id=ids, is_delete=False)
            serializer = self.get_serializer_class()(queryset, many=True)  # 注意使用many=True来序列化查询集
            if serializer.data:  # 检查序列化后的数据是否为空
                return Response(data=serializer.data, status=status.HTTP_200_OK)
            else:
                return Response(status=status.HTTP_404_NOT_FOUND)  # 如果没有找到对应的记录，返回404状态码
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)  # 如果没有提供id参数，返回400状态码

    # 修改班级内容
    @action(methods=['POST'], detail=False, url_name='update-clazz', url_path='update-clazz')
    def UpdateClazz(self, request, *args, **kwargs):
        queryset = self.get_queryset().get(id=request.data['id'], is_delete=False)
        serializer = self.get_serializer(instance=queryset, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        if serializer.data:
            return Response(data=serializer.data, status=status.HTTP_200_OK)
        return Response(status=status.HTTP_404_NOT_FOUND)  # 如果没有找到对应的记录，返回404状态码

    # 修改班级的状态
    @action(methods=['POST'], detail=False, url_path='clazz-status', url_name='clazz-status')
    def modi_clazz_status(self, request, *args, **kwargs):
        queryset = self.get_queryset().get(id=request.data['id'], is_delete=False)
        serializer = self.get_serializer(instance=queryset, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        if serializer.data:
            return Response(data=serializer.data, status=status.HTTP_200_OK)
        return Response(status=status.HTTP_404_NOT_FOUND)  # 如果没有找到对应的记录，返回404状态码

    def destroy(self, request, *args, **kwargs):
        # 删除班级
        url = request.path
        id = url.rsplit("/")[-1]
        queryset = self.get_queryset().filter(id=id)
        if queryset:
            queryset.update(is_delete=True, update_time=datetime.now())
            return Response(data={"message": "删除成功"}, status=status.HTTP_200_OK)
        return Response(data={"message": "删除失败"}, status=status.HTTP_400_BAD_REQUEST)

    @action(methods=['DELETE'], detail=False, url_path='delect-All-Clazz', url_name='delect-All-Clazz')
    def delectAll(self, request, *args, **kwargs):
        # 逻辑(软)删除,删除全部班级
        self.get_queryset().filter(pk__in=request.data).update(is_delete=True, delete_time=datetime.now())
        return Response(status=status.HTTP_204_NO_CONTENT)

    # 切换班级(查询班级名)
    @action(methods=['GET'], detail=False, url_path='switch-class', url_name='switch-class')
    def switchClass(self, request, *args, **kwargs):
        # 查询所有可用的班级,没有毕业的班级,没有上出的班级
        queryset = self.get_queryset().filter(is_delete=False, state=False)

        # 序列化满足条件的数据
        serialize = self.get_serializer(queryset, many=True)
        print("queryset", "//////////", serialize.data)
        return Response(data=serialize.data, status=status.HTTP_200_OK)

    # 根据用户选中的班级修改用户的班级id
    @action(methods=['POST'], detail=False, url_path='clazz-update_id', url_name='clazz-update_id')
    def switchClass_update_id(self, request, *args, **kwargs):
        clazz_id = request.data.get('id')  # 获取传入的参数 ,该id 是要修改的班级id
        if not clazz_id:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        user_id = request.user.id  # 从token 中获取当前用户id
        user=User.objects.get(id=user_id) #获取user 的实例化对象
        clazz=Clazz.objects.get(id=clazz_id) #获取clazz 的实例化对象
        user.clazz_id=clazz.id
        user.save()
        serialize=self.get_serializer(clazz)
        return Response(data=serialize.data,status=status.HTTP_200_OK)
    #123

